// 设置 Cookie
export function setCookie(name, value, minute = 30, path = '/') {
    let expires = '';
    if (minute) {
        const date = new Date();
        date.setTime(date.getTime() + (minute * 60 * 1000)); // 将天数转为毫秒
        expires = `expires=${date.toUTCString()}`;
    }
    document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=${path}`;
}

// 获取 Cookie
export function getCookie(name) {
    // let str = "username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
    // let reg = /([a-zA-Z0-9_-]+)=([^;]*)/g;
    // let match;
    // let cookies = {};

    // while (match = reg.exec(str)) {
    // let key = match[1];  // 键名
    // let value = match[2];  // 值
    // cookies[key] = value;  // 将键值对存入对象
    // }

    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? decodeURIComponent(match[2]) : null;
}

// 删除 Cookie
export function deleteCookie(name, path = '/') {
    this.setCookie(name, '', -1, path);
}

// 检查是否存在某个 Cookie
export function checkCookie(name) {
    return this.getCookie(name) !== null;
}

// 获取所有的 cookies
export function getAllCookies() {
    const cookies = document.cookie.split('; ');
    const cookieObj = {};
    cookies.forEach(cookie => {
        const [key, value] = cookie.split('=');
        cookieObj[key] = decodeURIComponent(value);
    });
    return cookieObj;
}
